package com.yantong.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.yantong.constant.ConfigKey;
import com.yantong.pojo.OssConfig;
import com.yantong.service.ConfigService;
import com.yantong.service.OssService;
import com.yantong.utils.DateUtils;
import com.yantong.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云OSS服务
 * @author kanghaixin
 * @date 2018/8/27.14:09
 */
@Service
public class OssServiceImpl implements OssService {
    //阿里云API的外网域名
    private static String ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
    //阿里云API的密钥Access Key ID
    private static String ACCESS_KEY_ID = "LTAI4Fbp4FrYjCdfiTp1XDWF";
    //阿里云API的密钥Access Key Secret
    private static String ACCESS_KEY_SECRET = "yBKeWDh7sx0X60IiheijcKrZDgbpgf";
    //阿里云API的bucket名称
    private static String BACKET_NAME = "download-pkg";
    //阿里云API的文件夹名称
    private static final String FOLDER = "data/upload/images/";
    /**
     * 用户自定义域名
     */
    private static String prefix = "https://down.919cyb.com/";

    @Autowired
    private ConfigService configService;

    private static final Logger logger = LoggerFactory.getLogger(OssServiceImpl.class);
    private static OSSClient ossClient;


//    @PostConstruct
    public void init() {
        OssConfig config = configService.getOssConfig(ConfigKey.OSS_CONFIG.name());
        if (config != null) {
            ACCESS_KEY_ID = StringUtils.isEmpty(config.getAccessKeyId())?ACCESS_KEY_ID: config.getAccessKeyId();
            ACCESS_KEY_SECRET = StringUtils.isEmpty(config.getAccessKeySecret())?ACCESS_KEY_SECRET: config.getAccessKeySecret();
            BACKET_NAME = StringUtils.isEmpty(config.getBucket())?BACKET_NAME: config.getBucket();
            ENDPOINT = StringUtils.isEmpty(config.getEndPoint())?ENDPOINT: config.getEndPoint();
            prefix = StringUtils.isEmpty(config.getDefineUrl())?prefix:config.getDefineUrl();
        }
        ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    @Override
    public String uploadImg(MultipartFile file, String folder) {
        if (StringUtils.isEmpty(folder)) {
            folder = FOLDER.concat(DateUtils.format(new Date())).concat("/");
        }
        String key = null;
        try {
            if (ossClient == null) {
                this.init();
            }
            InputStream is = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //文件大小
            Long fileSize = file.getSize();
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            //上传的文件的长度
            metadata.setContentLength(is.available());
            //指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("public");
            //指定该Object下设置Header
            metadata.setHeader("Pragma", "public");
            //指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            //如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            //上传文件   (上传文件流的形式)
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            fileName = MD5Utils.encrypt(UUID.randomUUID().toString());
            key =  folder + fileName + fileExtension;
            PutObjectResult putResult = ossClient.putObject(BACKET_NAME, key, is, metadata);
            logger.info("--------------上传返回值：---------"+ JSONObject.toJSONString(putResult));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }
        if (StringUtils.isNotEmpty(key)) {
            key = prefix.concat(key);
        }
        return key;
    }

    @Override
    public String uploadImg(InputStream inputStream, String folder) {
        if (StringUtils.isEmpty(folder)) {
            folder = FOLDER.concat(DateUtils.format(new Date())).concat("/");
        }
        String key = null;
        try {
            if (ossClient == null) {
                this.init();
            }
            //创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            //上传的文件的长度
            metadata.setContentLength(inputStream.available());
            //指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("public");
            //指定该Object下设置Header
            metadata.setHeader("Pragma", "public");
            //指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            //如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(".jpg"));
            //上传文件   (上传文件流的形式)
            String fileName = MD5Utils.encrypt(UUID.randomUUID().toString());
            key =  folder + fileName + ".jpg";
            PutObjectResult putResult = ossClient.putObject(BACKET_NAME, key, inputStream, metadata);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        }finally {
 			try {
 				if (inputStream != null) {
 					inputStream.close();
 				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
        if (StringUtils.isNotEmpty(key)) {
            key = prefix.concat(key);
        }
        return key;
    }


    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        //默认返回类型
        return "image/jpeg";
    }

}
